package com.hdu.metrics_center.redisCommand;

import com.hdu.metrics_center.enums.RedisCommandType;
import com.hdu.metrics_center.metrics.MetricsValue;
import com.hdu.metrics_center.utils.JedisUtils;
import com.hdu.metrics_center.enums.MetricsQueryResultType;
import com.hdu.metrics_center.metrics.MetricsExecuteReq;
import com.hdu.metrics_center.metrics.MetricsExecuteResult;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.parseObject;

@Component
public class HGetAllRedisCommand implements RedisCommand {


    @Override
    public RedisCommandType support() {
        return RedisCommandType.HGETALL;
    }

    @Override
    public MetricsExecuteResult operate(MetricsExecuteReq metricsExecuteReq) {
        Jedis jedis = JedisUtils.getJedis();
        Map<String, MetricsValue> deserializedValues = jedis
                .hgetAll(metricsExecuteReq.getKey())
                .entrySet()
                .stream()
                .collect
                        (
                                Collectors.toMap(
                                        Map.Entry::getKey,
                                        entry -> parseObject(entry.getValue(), MetricsValue.class)
                                )
                        );
        return MetricsExecuteResult
                .builder()
                .type(MetricsQueryResultType.MAP)
                .value(deserializedValues)
                .reqUuid(metricsExecuteReq.getReqUuid())
                .build();
    }
}
